//
//  composeViewController.swift
//  SHWeibo2.0
//
//  Created by 黄礼潮 on 16/3/2.
//  Copyright © 2016年 黄礼潮. All rights reserved.
//

import UIKit
import SVProgressHUD
import HMImagePicker
private let CZTextLength:Int = 140
private let CZMaxlength:CGFloat = 10
private let CZCellectionCellIndeifer = "CZCellectionCellIndeifer"
private let CZMaxpicture = 6
class ComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
        // Do any additional setup after loading the view.
        //监听文本发生变化  让键盘成为第一响应者
        NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyBoard:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //叫出键盘
        textView.becomeFirstResponder()
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        //退出键盘
        textView.resignFirstResponder()
    }
    
    @objc private func keyBoard(notification:NSNotification){
        
       //print(notification)
        //根据键盘出现的距离，设置toolbar
        let rect = (notification.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        let duration = (notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as!NSNumber).doubleValue
        let offset = view.bounds.height - rect.origin.y
        //更新toolbar位置
        toobar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            //在动画时间内，强行更新视图的所有约束，保证toobar和键盘一起叫出来
            self.view.layoutIfNeeded()
        }
    }
    
    //监听方法
    @objc private func cancelButton(){
    
        dismissViewControllerAnimated(true, completion:nil)
    
    }
    //发布微博
    @objc private func savePoseButton(){
    
        guard let text = textView.text else{
        
            return
        }
        //判断文本的长度
        
        NetworkTools.shardTools.saveText(text, image: images.first) { (result) -> () in
            
            //判断文字的长度
            if text.characters.count > CZTextLength {
            
               SVProgressHUD.showInfoWithStatus("输入的文本太长", maskType: .Gradient)
                return
            }
            
            
            if result == nil {
               //发布不成功
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            //发布完成
            SVProgressHUD.showInfoWithStatus("发布成功")
            
            //延迟退出发布微博界面
           dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(Double(NSEC_PER_SEC) * 1.0)),dispatch_get_main_queue() , { () -> Void in
              self.cancelButton()
           })
        }
        
    }
    //选择图片
    @objc private func selectPicture(){
    
       print("\(classForCoder)\(__FUNCTION__)")
    }
    //选择表情
    @objc private func selectEmotion(){
    
    
    }
    //工具栏
    private lazy var toobar:UIToolbar = UIToolbar()
    //加载文本视图
    private lazy var textView:ComposeTextView = ComposeTextView()
// MARK: - 添加collectionView来发布图片
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: CZCollectionFlowLayout())
    //定义图片数组
    private var images:[UIImage] = [UIImage]()
    //用户选中时的索引
    private var selectedIdx:Int = 1
    
    //选中素材集合，可以和底层的相册通讯
    private var selectedAssects:[PHAsset]?
    


}
// MARK: - 自动布局的类

private class  CZCollectionFlowLayout:UICollectionViewFlowLayout{

     //此方法是collectionView准备布局的时候调用，collectionView的bounds已经设置好了
    private override func prepareLayout() {
        super.prepareLayout()
        
        let margin:CGFloat = 10
        let count:CGFloat = 3
        let width = (collectionView!.bounds.width - (count - 1) * margin) / count
        itemSize = CGSize(width: width, height: width)
        minimumLineSpacing = margin
        
        minimumInteritemSpacing = margin
    }


}
// MARK: - 遵守协议
extension ComposeViewController: ComposeViewCellDeledate {

    func addPictureClick(cell: ComposeViewCell) {
        //取出图片的索引
        self.selectedIdx = collectionView.indexPathForCell(cell)!.item
        let picker = HMImagePickerController(selectedAssets: selectedAssects)
        picker.maxPickerCount = 6
        picker.pickerDelegate = self
        // 允许编辑，能够裁切照片，并且返回正方形的图片，图片尺寸小，方便上传！
        // 在开发中，选择头像的时候非常有用！
        // picker.allowsEditing = true

        presentViewController(picker, animated: true, completion: nil)
        
    }
    func removePictureClick(cell: ComposeViewCell) {
      //根据对应的cell获取 indexPath
      let  indexPath = collectionView.indexPathForCell(cell)!
      //根据indexPath 移除数据源中的images数组的图像
      images.removeAtIndex(indexPath.item)
      // 刷新数据
       collectionView.reloadData()
    }
    
}
// MARK: - 遵守HMImagePicker代理协议
extension ComposeViewController:HMImagePickerControllerDelegate{
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        self.images = images
        self.selectedAssects = selectedAssets
        collectionView.reloadData()
        
        //退出控制器
        dismissViewControllerAnimated(true, completion:nil)
    }

}

// MARK: - 在相册中选择图片  在开发相册的时候，必须考虑缓存

//extension ComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//      //  print(info)
//        //取出图片
//        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
//        //指定目标宽度
//        let width:CGFloat = 600
//        let height = width * image.size.width / image.size.height
//        
//        //裁剪，获得图片 是内存进行优化，不然的话内存消耗很高
//        image.cz_drawImage(CGSize(width: width, height: height)) { (image) -> () in
//            //判断索引的位置
//            if self.selectedIdx >= self.images.count{
//            
//                //追加
//                self.images.append(image)
//            }else{
//                self.images[self.selectedIdx ] = image
//
//            }
//            //刷新数据
//            self.collectionView.reloadData()
//        }
//        //自己退出picker控制器
//        dismissViewControllerAnimated(true, completion: nil)
//    }

//}

// MARK: - 数据源和代理方法
extension ComposeViewController:UICollectionViewDataSource,UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (images.count >= CZMaxpicture) ? images.count : images.count + 1
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let  cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZCellectionCellIndeifer, forIndexPath: indexPath) as! ComposeViewCell
        //设置代理
        cell.delegate = self //不能写可选项，代理方法进不来
        
        //设置图像  前面数组加1了 ，所以这里要做一个判断
        let image:UIImage? = (indexPath.item == images.count) ? nil : images[indexPath.item]
        
        cell.image = image
        
        return cell
    }

}

extension ComposeViewController:UITextViewDelegate{

   //检测文本发生变化
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = true
    }

}
extension ComposeViewController{
    
    private func setupUI(){
        //添加导航栏的内容
        addBar()
        //2.添加toolbar
        prepareToobar()
        //3.添加textView
        prepareTextView()
        
        //4.添加collectionView
        prepareCollectionView()

    }
    //添加导航栏的内容
    private func addBar(){
    
        let postButton:UIButton = UIButton(cz_butitle:"发布",color:UIColor.whiteColor(), backImageName:"common_button_orange", fontSize: 14)
        postButton.addTarget(self, action:"savePoseButton", forControlEvents:.TouchUpInside)
        postButton.setTitleColor(UIColor.lightGrayColor(), forState:.Disabled)
        postButton.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState:.Disabled)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView:postButton)
        
        //设置发布按钮的属性  在导航栏中设置控件时，不需要设置x y 只用设置宽度和高度
        postButton.frame = CGRect(x: 0, y: 0, width: 50, height: 35)
        //需要有内容才能发布
        navigationItem.rightBarButtonItem!.enabled = false
        /**
        *  添加导航栏左边的按钮，和设置title
        */
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"取消", style:.Plain, target:self, action:"cancelButton")
        
        let attText = NSMutableAttributedString(string:"发微博\n", attributes:[NSFontAttributeName:UIFont.systemFontOfSize(15),
            NSForegroundColorAttributeName:UIColor.darkGrayColor()])
        let title = UILabel()
 
        let nameText = NSAttributedString(string:UserAccount.shardUserAccount.screen_name!, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(12),
            NSForegroundColorAttributeName:UIColor.lightGrayColor()])

         attText.appendAttributedString(nameText)
        
         title.attributedText = attText
         title.numberOfLines = 0
         title.sizeToFit()
         title.textAlignment = .Center
        
         navigationItem.titleView = title
        
    
    }
    
    private func prepareToobar(){
       //添加控件
        view.addSubview(toobar)
        
        //自动布局
        toobar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        //添加五个按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmotion"],
            ["imageName": "compose_add_background"]]
        
        toobar.items = [UIBarButtonItem]()
        
        for dict in itemSettings{
        
            let imageName = dict["imageName"]
            let itemButton = UIButton(cz_butitle:nil, imageName:imageName)
        
            //来判断字典中是否有actionName
            if let actionName = dict["actionName"]{
            //如果用常量创建的话，需要使用Selsect(actionName)构造函数
                itemButton.addTarget(self, action: Selector(actionName), forControlEvents:.TouchUpInside)
            }
            //往toolbar中添加按钮
            toobar.items?.append(UIBarButtonItem(customView: itemButton))
            //添加弹簧效果
            toobar.items?.append(UIBarButtonItem(barButtonSystemItem:.FlexibleSpace, target:nil, action: nil))
            
        }
        //移除嘴壶一个弹簧的效果
        toobar.items?.removeLast()
 
    }
    
    private func prepareTextView(){
        //添加textView
        view.addSubview(textView)
//        textView.backgroundColor = UIColor.yellowColor()
        
        //自动布局
        textView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(toobar.snp_top)
            //snp_topLayoutGuideBottom，如果有导航栏/状态栏...能够让开，
            make.top.equalTo(self.snp_topLayoutGuideBottom)
        }
        
        textView.delegate = self
        textView.maxlength = Int(CZMaxlength)
        
        //测试文本
         // textView.text = "发现点新鲜事...发现点新鲜事...发现点新鲜事...发现点新鲜事...发现点新鲜事..."
//        textView.font = UIFont.systemFontOfSize(12)
//        textView.textColor = UIColor.lightGrayColor()
  //        textView.placehoderLabel =  "发现点新鲜事..."
     
    
    }
    
    private func prepareCollectionView(){
    
        //添加视图
        textView.addSubview(collectionView)
        collectionView.backgroundColor = UIColor.cz_colorWithHex(0xF5F5F5)
        
       //自动布局
        let margin = CZCellViewLayout.margin
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view).offset(margin)
            make.right.equalTo(view).offset(-margin)
            make.height.equalTo(collectionView.snp_width)
            make.top.equalTo(textView).offset(100)
        }
        //设置数据源和代理
        collectionView.dataSource = self
        collectionView.delegate = self
        //注册可重用Cell
        collectionView.registerClass(ComposeViewCell.self, forCellWithReuseIdentifier: CZCellectionCellIndeifer)
    }
}
